// 项目管理API接口
import { Project, GetProjectsParams, ProjectStats, ApiResponse } from '../types/project';
import { projectData as mockProjectData, getProjectStats } from '../data/projectData';

// API基础路径
const API_BASE = '/api/projects';

// 模拟项目API
const mockProjectApi = {
  // 获取项目列表
  getProjects: async (params: GetProjectsParams = {}): Promise<ApiResponse<Project[]>> => {
    const { page = 1, pageSize = 10, search, status, priority } = params;
    
    // 过滤数据
    let filteredData = mockProjectData;
    
    if (search) {
      filteredData = filteredData.filter(project => 
        project.name.includes(search) || 
        project.code.includes(search) ||
        project.description?.includes(search) ||
        project.manager.includes(search)
      );
    }
    
    if (status) {
      filteredData = filteredData.filter(project => project.status === status);
    }
    
    if (priority) {
      filteredData = filteredData.filter(project => project.priority === priority);
    }
    
    // 分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);
    
    // 模拟延迟
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return {
      data: paginatedData,
      total: filteredData.length,
      success: true,
      message: '获取项目列表成功'
    };
  },

  // 获取项目详情
  getProject: async (id: number): Promise<Project> => {
    const project = mockProjectData.find(p => p.id === id);
    if (!project) {
      throw new Error('项目不存在');
    }
    
    await new Promise(resolve => setTimeout(resolve, 200));
    return project;
  },

  // 创建项目
  createProject: async (project: Omit<Project, 'id' | 'createdAt' | 'updatedAt'>): Promise<Project> => {
    const newProject: Project = {
      ...project,
      id: Math.max(...mockProjectData.map(p => p.id)) + 1,
      createdAt: new Date().toISOString().split('T')[0],
      updatedAt: new Date().toISOString().split('T')[0]
    };
    
    mockProjectData.push(newProject);
    await new Promise(resolve => setTimeout(resolve, 500));
    
    return newProject;
  },

  // 更新项目
  updateProject: async (id: number, updates: Partial<Project>): Promise<Project> => {
    const index = mockProjectData.findIndex(p => p.id === id);
    if (index === -1) {
      throw new Error('项目不存在');
    }
    
    const updatedProject = {
      ...mockProjectData[index],
      ...updates,
      updatedAt: new Date().toISOString().split('T')[0]
    };
    
    mockProjectData[index] = updatedProject;
    await new Promise(resolve => setTimeout(resolve, 300));
    
    return updatedProject;
  },

  // 删除项目
  deleteProject: async (id: number): Promise<void> => {
    const index = mockProjectData.findIndex(p => p.id === id);
    if (index === -1) {
      throw new Error('项目不存在');
    }
    
    mockProjectData.splice(index, 1);
    await new Promise(resolve => setTimeout(resolve, 200));
  },

  // 获取项目统计
  getProjectStats: async (): Promise<ProjectStats> => {
    await new Promise(resolve => setTimeout(resolve, 200));
    return getProjectStats();
  }
};

// 真实项目API（根据配置决定使用模拟还是真实API）
const projectApi = {
  getProjects: async (params: GetProjectsParams = {}): Promise<ApiResponse<Project[]>> => {
    // 根据环境配置决定使用模拟API还是真实API
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProjectApi.getProjects(params);
    }
    
    // 真实API调用
    const queryParams = new URLSearchParams();
    if (params.page) queryParams.append('page', params.page.toString());
    if (params.pageSize) queryParams.append('pageSize', params.pageSize.toString());
    if (params.search) queryParams.append('search', params.search);
    if (params.status) queryParams.append('status', params.status);
    if (params.priority) queryParams.append('priority', params.priority);
    
    const response = await fetch(`${API_BASE}?${queryParams}`);
    if (!response.ok) {
      throw new Error('获取项目列表失败');
    }
    
    return response.json();
  },

  getProject: async (id: number): Promise<Project> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProjectApi.getProject(id);
    }
    
    const response = await fetch(`${API_BASE}/${id}`);
    if (!response.ok) {
      throw new Error('获取项目详情失败');
    }
    
    return response.json();
  },

  createProject: async (project: Omit<Project, 'id' | 'createdAt' | 'updatedAt'>): Promise<Project> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProjectApi.createProject(project);
    }
    
    const response = await fetch(API_BASE, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(project)
    });
    
    if (!response.ok) {
      throw new Error('创建项目失败');
    }
    
    return response.json();
  },

  updateProject: async (id: number, updates: Partial<Project>): Promise<Project> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProjectApi.updateProject(id, updates);
    }
    
    const response = await fetch(`${API_BASE}/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(updates)
    });
    
    if (!response.ok) {
      throw new Error('更新项目失败');
    }
    
    return response.json();
  },

  deleteProject: async (id: number): Promise<void> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProjectApi.deleteProject(id);
    }
    
    const response = await fetch(`${API_BASE}/${id}`, {
      method: 'DELETE'
    });
    
    if (!response.ok) {
      throw new Error('删除项目失败');
    }
  },

  getProjectStats: async (): Promise<ProjectStats> => {
    const useMock = process.env.NODE_ENV === 'development' || !process.env.REACT_APP_API_BASE_URL;
    
    if (useMock) {
      return mockProjectApi.getProjectStats();
    }
    
    const response = await fetch(`${API_BASE}/stats`);
    if (!response.ok) {
      throw new Error('获取项目统计失败');
    }
    
    return response.json();
  }
};

export { projectApi };
export default projectApi;